﻿<%@ WebHandler Language="C#" Class="QualityDashBoard" %>

using System;
using System.IO;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using System.Collections.Generic;
using System.Data;
using System.Text;
using ReportBusiness;
using System.Net;

/*
 * Description: 质量看板
 * Copyright (c) : 通力凯顿（北京）系统集成有限公司
 * Writer:zhunan
 * Date:2022.10.20
 */

public class QualityDashBoard : IHttpHandler
{
    uMESReportOracleDAL dal = new uMESReportOracleDAL();
    public bool IsReusable { get { return false; } }
    public void ProcessRequest(HttpContext context)
    {
        string requestjson = "";
        using (StreamReader reader = new StreamReader(context.Request.InputStream)) { requestjson = reader.ReadToEnd(); }
        JObject jObject = JsonConvert.DeserializeObject(requestjson) as JObject;
        if (jObject["type"] != null)
        {
            try
            {
                Result r = new Result();
                context.Response.ContentType = "text/json";
                string type = jObject["type"].ToString();
                switch (type)
                {
                    case "getPassRate":
                        r = getPassRate(jObject);//合格率
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "getPassRateDetail":
                        r = getChartDetail(jObject);//合格率明细
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "getDefectQty":
                        r = getDefectQty(jObject);//超差数
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "getDefectChartDetail":
                        r = getChartDetail(jObject);//超差数明细
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "getReworkQty":
                        r = getReworkQty(jObject);//返修数
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "getReworkChartDetail":
                        r = getChartDetail(jObject);//返修数明细
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "getLossQty":
                        r = getLossQty(jObject);//报废数
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "getLossChartDetail":
                        r = getChartDetail(jObject);//报废数明细
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "getYiCiJiaoJianHeGeLv":
                        r = getYiCiJiaoJianHeGeLv(jObject);//一次交检合格率
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "getYiCiJiaoJianHeGeLvDetail":
                        r = getYiCiJiaoJianHeGeLvDetail(jObject);//一次交检合格率--批次明细
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "getNoPassSpecDetail":
                        r = getNoPassSpecDetail(jObject);//一次交检合格率--批次工序明细
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "getFinishCheckPassRate":
                        r = getFinishCheckPassRate(jObject);//成检合格率
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "getFinishCheckPassRateDetail":
                        r = getFinishCheckPassRateDetail(jObject);//成检合格率--明细
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    default:
                        break;
                }
            }
            catch (Exception e)
            {
                Result r = new Result();
                r.data = null;
                r.meta = new Result.Meta(500, e.Message);
                r.total = 0;
                context.Response.ContentType = "text/json";
                context.Response.Write(JsonConvert.SerializeObject(r));
            }
        }
    }

    string getQuerySql(JObject jObject)
    {
        string sql = @"
SELECT csd.containername,csd.workflowstepname,csd.workcentername,csd.reportemployeename,csd.reportdate,csd.reportqty,
       csd.checkemployeename,csd.checkdate,NVL(csd.passqty,0) passqty,NVL(csd.lossqty,0) lossqty,NVL(csd.defectqty,0) defectqty,NVL(csd.reworkqty,0) reworkqty
FROM containersteprecord csd
LEFT JOIN containercurrentinfo cci ON cci.containerid = csd.containerid
WHERE csd.checkdate IS NOT NULL AND cci.originalfactoryid = csd.factoryid AND csd.workcentername <> '工装工具夹具工区'";

        if (jObject["factoryid"] != null && jObject["factoryid"].ToString() != "")
        {
            sql += string.Format(" AND cci.originalfactoryid = '{0}'", jObject["factoryid"].ToString());
        }

        if (jObject["selectdate"] != null && jObject["selectdate"].ToString() != "")
        {
            JArray arr = JArray.Parse(jObject["selectdate"].ToString());
            if (arr.Count == 2)
            {
                sql += string.Format(" AND csd.checkdate >= TO_DATE('{0} 00:00:00','yyyy-mm-dd hh24:mi:ss')", arr[0].ToString());
                sql += string.Format(" AND csd.checkdate <= TO_DATE('{0} 23:59:59','yyyy-mm-dd hh24:mi:ss')", arr[1].ToString());
            }
        }

        if (jObject["workcentername"] != null && jObject["workcentername"].ToString() != "")
        {
            sql += string.Format(" AND csd.workcentername = '{0}'", jObject["workcentername"].ToString());
        }

        if (jObject["seriesName"] != null)
        {
            if (jObject["seriesName"].ToString() == "合格率")
            {
                sql += " AND csd.reportqty <= csd.passqty";
            }
            if (jObject["seriesName"].ToString() == "不合格率")
            {
                sql += " AND csd.reportqty > csd.passqty";
            }
            if (jObject["seriesName"].ToString() == "超差数")
            {
                sql += " AND NVL(csd.defectqty,0) > 0";
            }
            if (jObject["seriesName"].ToString() == "返修数")
            {
                sql += " AND NVL(csd.reworkqty,0) > 0";
            }
            if (jObject["seriesName"].ToString() == "报废数")
            {
                sql += " AND NVL(csd.lossqty,0) > 0";
            }
        }
        return sql;
    }

    //合格率
    Result getPassRate(JObject jObject)
    {
        string sql = @"
SELECT t.workcentername,COUNT(t.workflowstepname) total,SUM(CASE WHEN t.reportqty <= t.passqty THEN 1 ELSE 0 END) pass,
       SUM(CASE WHEN t.reportqty > t.passqty THEN 1 ELSE 0 END) notpass,
       ROUND(SUM(CASE WHEN t.reportqty <= t.passqty THEN 1 ELSE 0 END) / COUNT(t.workflowstepname),4) * 100 passrate,
       ROUND(SUM(CASE WHEN t.reportqty > t.passqty THEN 1 ELSE 0 END) / COUNT(t.workflowstepname),4) * 100 notpassrate
FROM ({0}) t
GROUP BY t.workcentername
";
        sql = string.Format(sql, getQuerySql(jObject));
        DataTable dtResult = dal.GetDataTable(sql);
        foreach (DataColumn col in dtResult.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        Result r = new Result();
        r.data = dtResult;
        r.total = Convert.ToInt32(dtResult.Rows.Count);
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    //超差数
    Result getDefectQty(JObject jObject)
    {
        string sql = @"SELECT t.workcentername,SUM(t.defectQty) defectQty FROM ({0}) t GROUP BY t.workcentername";
        sql = string.Format(sql, getQuerySql(jObject));
        DataTable dtResult = dal.GetDataTable(sql);
        foreach (DataColumn col in dtResult.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        Result r = new Result();
        r.data = dtResult;
        r.total = Convert.ToInt32(dtResult.Rows.Count);
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    //返修数
    Result getReworkQty(JObject jObject)
    {
        string sql = @"SELECT t.workcentername,SUM(t.reworkqty) reworkqty FROM ({0}) t GROUP BY t.workcentername";
        sql = string.Format(sql, getQuerySql(jObject));
        DataTable dtResult = dal.GetDataTable(sql);
        foreach (DataColumn col in dtResult.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        Result r = new Result();
        r.data = dtResult;
        r.total = Convert.ToInt32(dtResult.Rows.Count);
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    //报废数
    Result getLossQty(JObject jObject)
    {
        string sql = @"SELECT t.workcentername,SUM(t.lossqty) lossqty FROM ({0}) t GROUP BY t.workcentername";
        sql = string.Format(sql, getQuerySql(jObject));
        DataTable dtResult = dal.GetDataTable(sql);
        foreach (DataColumn col in dtResult.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        Result r = new Result();
        r.data = dtResult;
        r.total = Convert.ToInt32(dtResult.Rows.Count);
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    //一次交检合格率
    Result getYiCiJiaoJianHeGeLv(JObject jObject)
    {
        string sql = @"
SELECT t1.workcentername,COUNT(t1.containername) total,SUM(CASE WHEN t1.status = '合格' THEN 1 ELSE 0 END) passqty,
       SUM(CASE WHEN t1.status = '不合格' THEN 1 ELSE 0 END) notpassqty,
       ROUND(SUM(CASE WHEN t1.status = '合格' THEN 1 ELSE 0 END)/COUNT(t1.containername),4) * 100 passrate,
       ROUND(SUM(CASE WHEN t1.status = '不合格' THEN 1 ELSE 0 END)/COUNT(t1.containername),4) * 100 notpassrate
FROM 
(
  SELECT t.workcentername,t.containername,CASE WHEN SUM(t.reportqty) <= SUM(t.passqty) THEN '合格' ELSE '不合格' END status
  FROM 
  (
     {0}
  ) t
  GROUP BY t.workcentername,t.containername
) t1
GROUP BY t1.workcentername
";
        sql = string.Format(sql, getQuerySql(jObject));
        DataTable dtResult = dal.GetDataTable(sql);
        foreach (DataColumn col in dtResult.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        Result r = new Result();
        r.data = dtResult;
        r.total = Convert.ToInt32(dtResult.Rows.Count);
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    //一次交检合格率明细
    Result getYiCiJiaoJianHeGeLvDetail(JObject jObject)
    {
        string sql = @"
SELECT t.mfgordername,t.mfgqty,t.productname,t.productdescription,t.workcentername,t.containername,t.originalqty,t.qty,NVL(SUM(t.lossqty),0) lossqty,
       NVL(SUM(t.defectqty),0) defectqty,NVL(SUM(t.reworkqty),0) reworkqty,
       CASE WHEN NVL(SUM(t.lossqty),0) + NVL(SUM(t.defectqty),0) + NVL(SUM(t.reworkqty),0) > 0 THEN '不合格' ELSE '合格' END status
FROM 
(
  SELECT csd.containername,csd.workflowstepname,csd.workcentername,csd.reportemployeename,csd.reportdate,csd.reportqty,
         csd.checkemployeename,csd.checkdate,NVL(csd.passqty,0) passqty,NVL(csd.lossqty,0) lossqty,NVL(csd.defectqty,0) defectqty,NVL(csd.reworkqty,0) reworkqty,
         cci.mfgordername,mfg.qty mfgqty,c.originalqty,cci.qty,cci.productname,cci.productdescription
  FROM containersteprecord csd
  LEFT JOIN containercurrentinfo cci ON cci.containerid = csd.containerid
  LEFT JOIN container c ON c.containerid = cci.containerid
  LEFT JOIN mfgorder mfg ON mfg.mfgorderid = cci.mfgorderid
  WHERE csd.checkdate IS NOT NULL AND cci.originalfactoryid = csd.factoryid";

        if (jObject["factoryid"] != null && jObject["factoryid"].ToString() != "")
        {
            sql += string.Format(" AND cci.originalfactoryid = '{0}'", jObject["factoryid"].ToString());
        }

        if (jObject["selectdate"] != null && jObject["selectdate"].ToString() != "")
        {
            JArray arr = JArray.Parse(jObject["selectdate"].ToString());
            if (arr.Count == 2)
            {
                sql += string.Format(" AND csd.checkdate >= TO_DATE('{0} 00:00:00','yyyy-mm-dd hh24:mi:ss')", arr[0].ToString());
                sql += string.Format(" AND csd.checkdate <= TO_DATE('{0} 23:59:59','yyyy-mm-dd hh24:mi:ss')", arr[1].ToString());
            }
        }

        if (jObject["workcentername"] != null && jObject["workcentername"].ToString() != "")
        {
            sql += string.Format(" AND csd.workcentername = '{0}'", jObject["workcentername"].ToString());
        }

        sql += @"
) t
GROUP BY t.mfgordername,t.mfgqty,t.productname,t.productdescription,t.workcentername,t.containername,t.originalqty,t.qty
";
        uMESPagingDataDTO dto = dal.GetPagingDataIns(sql, (int)jObject["currentPage"], (int)jObject["pageSize"]);
        DataTable dt = dto.DBTable;
        foreach (DataColumn col in dt.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        Result r = new Result();
        r.data = dt;
        r.total = Convert.ToInt32(dto.RowCount);
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    //一次交检合格率--工序明细
    Result getNoPassSpecDetail(JObject jObject)
    {
        string sql = @"
SELECT csd.workcentername,cci.productname,cci.productdescription,csd.containername,csd.workflowstepname,csd.reportemployeename,csd.reportdate,csd.reportqty,
       csd.checkemployeename,csd.checkdate,NVL(csd.passqty,0) passqty,NVL(csd.lossqty,0) lossqty,NVL(csd.defectqty,0) defectqty,NVL(csd.reworkqty,0) reworkqty
FROM containersteprecord csd
LEFT JOIN containercurrentinfo cci ON cci.containerid = csd.containerid
LEFT JOIN container c ON c.containerid = cci.containerid
LEFT JOIN mfgorder mfg ON mfg.mfgorderid = cci.mfgorderid
WHERE csd.checkdate IS NOT NULL AND cci.originalfactoryid = csd.factoryid";

        if (jObject["factoryid"] != null && jObject["factoryid"].ToString() != "")
        {
            sql += string.Format(" AND cci.originalfactoryid = '{0}'", jObject["factoryid"].ToString());
        }

        if (jObject["selectdate"] != null && jObject["selectdate"].ToString() != "")
        {
            JArray arr = JArray.Parse(jObject["selectdate"].ToString());
            if (arr.Count == 2)
            {
                sql += string.Format(" AND csd.checkdate >= TO_DATE('{0} 00:00:00','yyyy-mm-dd hh24:mi:ss')", arr[0].ToString());
                sql += string.Format(" AND csd.checkdate <= TO_DATE('{0} 23:59:59','yyyy-mm-dd hh24:mi:ss')", arr[1].ToString());
            }
        }

        if (jObject["workcentername"] != null && jObject["workcentername"].ToString() != "")
        {
            sql += string.Format(" AND csd.workcentername = '{0}'", jObject["workcentername"].ToString());
        }

        if (jObject["seriesName"] != null)
        {
            sql += " AND csd.passqty < csd.reportqty ";
        }

        DataTable dt = dal.GetDataTable(sql);
        foreach (DataColumn col in dt.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        Result r = new Result();
        r.data = dt;
        r.total = Convert.ToInt32(dt.Rows.Count);
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    string getFinishCheckPassRateSql(JObject jObject)
    {
        string sql = @"
    SELECT cci.workcentername,cci.containername,cci.productname,cci.productdescription,cfc.acceptanceqty2,cfc.lossqty,cfc.reworkqty,cfc.defectqty,
           ws.workflowstepname,cfc.createdate checkdate,e.fullname checker,csw.createdate reportdate,e2.fullname worker,
           CASE WHEN  cfc.lossqty + cfc.defectqty + cfc.reworkqty > 0 THEN '不合格' ELSE '合格' END status                                
    FROM containerfinishedcheckinfo cfc
    LEFT JOIN containercurrentinfo cci ON cci.containerid = cfc.containerid
    LEFT JOIN product p ON p.productid = cci.productid
    LEFT JOIN Workflowstep ws ON ws.workflowstepid = cfc.workflowstepid
    LEFT JOIN employee e ON e.employeeid = cfc.checkerid
    LEFT JOIN containerstepworkreport csw ON csw.containerid = cfc.containerid AND csw.Workflowstepid = cfc.workflowstepid AND csw.isuse = 0
    LEFT JOIN employee e2 ON e2.employeeid = csw.workerid
    WHERE cfc.isuse = 0 AND p.istopgz = 1";

        if (jObject["factoryid"] != null && jObject["factoryid"].ToString() != "")
        {
            sql += string.Format(" AND cci.originalfactoryid = '{0}'", jObject["factoryid"].ToString());
        }

        if (jObject["selectdate"] != null && jObject["selectdate"].ToString() != "")
        {
            JArray arr = JArray.Parse(jObject["selectdate"].ToString());
            if (arr.Count == 2)
            {
                sql += string.Format(" AND cfc.createdate >= TO_DATE('{0} 00:00:00','yyyy-mm-dd hh24:mi:ss')", arr[0].ToString());
                sql += string.Format(" AND cfc.createdate <= TO_DATE('{0} 23:59:59','yyyy-mm-dd hh24:mi:ss')", arr[1].ToString());
            }
        }

        if (jObject["workcentername"] != null && jObject["workcentername"].ToString() != "")
        {
            sql += string.Format(" AND cci.workcentername = '{0}'", jObject["workcentername"].ToString());
        }

        return sql;
    }

    //成检合格率
    Result getFinishCheckPassRate(JObject jObject)
    {
        string sql = @"
SELECT t.workcentername,COUNT(t.containername) total,SUM(CASE WHEN t.status = '合格' THEN 1 ELSE 0 END) passqty,
       SUM(CASE WHEN t.status = '不合格' THEN 1 ELSE 0 END) notpassqty,
       ROUND(SUM(CASE WHEN t.status = '合格' THEN 1 ELSE 0 END)/COUNT(t.containername),4) * 100 passrate,
       ROUND(SUM(CASE WHEN t.status = '不合格' THEN 1 ELSE 0 END)/COUNT(t.containername),4) * 100 notpassrate
FROM 
(
   {0}
)
t
GROUP BY t.workcentername
";
        sql = string.Format(sql, getFinishCheckPassRateSql(jObject));
        DataTable dtResult = dal.GetDataTable(sql);
        foreach (DataColumn col in dtResult.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        Result r = new Result();
        r.data = dtResult;
        r.total = Convert.ToInt32(dtResult.Rows.Count);
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    //成检合格率--明细
    Result getFinishCheckPassRateDetail(JObject jObject)
    {
        string sql = getFinishCheckPassRateSql(jObject);
        uMESPagingDataDTO dto = dal.GetPagingDataIns(sql, (int)jObject["currentPage"], (int)jObject["pageSize"]);
        DataTable dt = dto.DBTable;
        foreach (DataColumn col in dt.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        Result r = new Result();
        r.data = dt;
        r.total = Convert.ToInt32(dto.RowCount);
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    Result getChartDetail(JObject jObject)
    {
        string sql = getQuerySql(jObject);
        uMESPagingDataDTO dto = dal.GetPagingDataIns(sql, (int)jObject["currentPage"], (int)jObject["pageSize"]);
        DataTable dt = dto.DBTable;
        foreach (DataColumn col in dt.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        Result r = new Result();
        r.data = dt;
        r.total = Convert.ToInt32(dto.RowCount);
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }
}